﻿import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
import { WebSQL, WebSQLObject } from '../../providers/web-sql/web-sql';

/**
 * Generated class for the SqlitePage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
    selector: 'page-sqlite',
    templateUrl: 'sqlite.html',
})
export class SqlitePage {

    private db: WebSQLObject;
    private name: string;
    private score: number;
    private count: number;

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        private sqlite: WebSQL) {

        this.sqlite.create({
            name: 'data.db',
            version: '1.0',
            size: 2 * 1024 * 1024
        }).then((db: WebSQLObject) => {
            this.db = db;
        }).catch(e => console.log(e));
    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad SqlitePage');
    }

    createTable() {
        this.db.transaction((tx) => {
            tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (name, score)', [], (rs) => console.log(rs), (err) => console.log(err));
            tx.executeSql('INSERT INTO test_table VALUES (?,?)', ['Alice', 101], (rs) => console.log(rs), (err) => console.log(err));
            tx.executeSql('INSERT INTO test_table VALUES (?,?)', ['Betty', 202], (rs) => console.log(rs), (err) => console.log(err));
        });
    }

    insetData() {
        this.db.executeSql('INSERT INTO test_table VALUES (?,?)', [this.name, this.score]).then((rs) => console.log(rs)).catch(e => console.log(e));
    }

    countData() {
        this.db.executeSql('SELECT count(*) AS mycount FROM test_table', []).then((rs) => {
            this.count = rs.rows.item(0).mycount;
        }).catch(e => console.log(e));
    }
}
